package com.tjy.quartz.task;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tjy.common.utils.DateUtils;
import com.tjy.farmer.domain.FarmerAlarm;
import com.tjy.farmer.domain.FarmerAreaData;
import com.tjy.farmer.domain.FarmerLocationTaskVO;
import com.tjy.farmer.domain.Location;
import com.tjy.farmer.mapper.FarmerAlarmMapper;
import com.tjy.farmer.mapper.FarmerLocationInfoMapper;
import com.tjy.farmer.util.GeoUtils;
import com.tjy.quartz.websocket.MyWebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;
import java.util.stream.Collectors;

@Component("farmerLocationTask")
public class FarmerLocationTask {

    @Autowired
    private FarmerLocationInfoMapper farmerLocationInfoMapper;

    @Autowired
    private FarmerAlarmMapper farmerAlarmMapper;

    int insertMessage = 0;


    /**
     * 定时定位蜂农位置
     */
    @Transactional(rollbackFor = Exception.class)
    public void checkFarmerLocation() {
        List<FarmerLocationTaskVO> farmers = getAllFarmersWithAreaInfo();

        ObjectMapper objectMapper = new ObjectMapper();

        for (FarmerLocationTaskVO farmer : farmers) {
            String farmerName = farmer.getName();
            boolean farmerInResponsibleArea = isFarmerInResponsibleArea(farmer);
            if (farmerInResponsibleArea) {
                continue;
            }

            List<FarmerAlarm> farmerAlarms = farmerAlarmMapper.selectFarmerAlarmList(new FarmerAlarm(
                    farmer.getFarmerId(),
                    null,
                    null,
                    null,
                    null,
                    null,
                    0
            ));

            if (farmerAlarms.isEmpty()) {
                FarmerAlarm farmerAlarm = new FarmerAlarm(
                        farmer.getFarmerId(),
                        farmerName,
                        farmer.getFarmerPhone(),
                        farmer.getAreaName(),
                        DateUtils.getNowDate(),
                        1,
                        0
                );

                farmerAlarmMapper.insertFarmerAlarm(farmerAlarm);

                String farmerAlarmsJson = null;
                try {
                    farmerAlarmsJson = objectMapper.writeValueAsString(farmerAlarm);
                    MyWebSocketServer.sendToAllAdmin(farmerAlarmsJson);
                } catch (JsonProcessingException e) {
                    // 处理JSON转换异常
                    e.printStackTrace();
                    // 可以发送错误信息给前端
                    MyWebSocketServer.sendToAllAdmin("获取告警信息失败: " + e.getMessage());
                }

            }
        }


    }



    public List<FarmerLocationTaskVO> getAllFarmersWithAreaInfo() {
        // 查询所有蜂农位置信息
        List<FarmerAreaData> dataList =
                farmerLocationInfoMapper.selectFarmerLocationInfoAll();

        // 按蜂农姓名分组，收集每个蜂农的所有区域边界点
        Map<String, FarmerLocationTaskVO> farmerMap = new HashMap<>();

        for (FarmerAreaData data : dataList) {
            String farmerName = data.getFarmerName();

            // 如果是新蜂农，创建Farmer对象
            if (!farmerMap.containsKey(farmerName)) {
                Location farmerLocation = new Location(data.getFarmerLongitude(), data.getFarmerLatitude(), 0);
                FarmerLocationTaskVO farmer = new FarmerLocationTaskVO(data.getFarmerId(), farmerName, data.getFarmerPhone()
                        , farmerLocation, data.getAreaName(), new ArrayList<>());
                farmerMap.put(farmerName, farmer);
            }

            // 添加边界点到蜂农的区域边界列表
            FarmerLocationTaskVO farmer = farmerMap.get(farmerName);
            Location boundaryPoint = new Location(data.getBoundaryLongitude(), data.getBoundaryLatitude(), data.getPointOrder());
            farmer.getAreaBoundary().add(boundaryPoint);
        }

        // 去重边界点并返回结果
        return farmerMap.values().stream()
                .peek(farmer -> {
                    // 移除重复的边界点
                    List<Location> uniqueBoundaries = farmer.getAreaBoundary().stream()
                            .distinct()
                            .collect(Collectors.toList());
                    farmer.setAreaBoundary(uniqueBoundaries);
                })
                .collect(Collectors.toList());
    }


    /**
     * 判断蜂农是否在自己负责的区域内
     * @param farmer 蜂农信息
     * @return 如果在区域内，返回true；否则返回false
     */
    public boolean isFarmerInResponsibleArea(FarmerLocationTaskVO farmer) {
        if (farmer == null || farmer.getLocation() == null ||
                farmer.getAreaBoundary() == null || farmer.getAreaBoundary().isEmpty()) {
            // 数据不完整，无法判断
            return false;
        }

        List<Location> areaBoundary = farmer.getAreaBoundary();
        // 按 pointOrder 升序排序（1→2→3→...）
        List<Location> orderedPolygon = areaBoundary.stream()
                .sorted(Comparator.comparingInt(Location::getPointOrder)) // 核心：按pointOrder排序
                .collect(Collectors.toList());

        // 使用地理工具类判断点是否在多边形内
        return GeoUtils.isPointInPolygon(farmer.getLocation(), orderedPolygon);
    }


}
